package com.scqkxx.gamebox.utils;

import android.support.annotation.NonNull;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.SaveCallback;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zsx on 2018/8/15.
 */

public class SaveLeanFileUtils {

    public static void save(String fileName, String filePath, @NonNull OnSaveInBackground onSaveInBackground) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                AVFile file = AVFile.withAbsoluteLocalPath(fileName, filePath);
                file.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if (null == e) {
                            emitter.onNext(file.getUrl());
                        } else {
                            emitter.onError(new Throwable("网络请求失败："+e.getMessage()));
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        onSaveInBackground.onSubscribe(d);
                    }

                    @Override
                    public void onNext(String object) {
                        onSaveInBackground.onSuccess(object);
                    }

                    @Override
                    public void onError(Throwable e) {
                        onSaveInBackground.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public interface OnSaveInBackground {
        void onSuccess(String url);

        void onError(String e);

        void onSubscribe(Disposable d);
    }
}
